package com.jfs.envent.listener;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jfs.constant.CommonConstant;
import com.jfs.entity.Device;
import com.jfs.envent.entity.DeviceOfflineEventEntity;
import com.jfs.health.HealthCheckReactor;
import com.jfs.health.RegistryDevice;
import com.jfs.service.DeviceService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @Description 设备离线监听者
 * @E-mail cwm3412638@163.com
 * @Author cwm
 * @Date 2022/8/1
 */
@Component
@Slf4j
@AllArgsConstructor
public class DeviceOfflineEventListener implements ApplicationListener<DeviceOfflineEventEntity> {
    private final DeviceService deviceService;
    private final HealthCheckReactor healthCheckReactor;
    private final static ReentrantLock LOCK =new ReentrantLock(true);

    @Override
    @Async
    @Transactional
    public void onApplicationEvent(DeviceOfflineEventEntity event) {
        try {
            if (log.isDebugEnabled()) {
                log.debug("【设备号:{},设备ip:{},设备端口号:{}】，设备离线：{}", event.getDeviceID(), event.getIp(), event.getPort(), JSONUtil.toJsonStr(event));
            }
            //1.把设备从注册表中移除
            RegistryDevice.remove(event.getDeviceID());
            healthCheckReactor.stopSeceduleCheck(CommonConstant.BEAT_TASK_KEY_PREFIX + event.getDeviceID());
            //2.修改设备状态为离线
            LOCK.lock();
            this.deviceService.update(Wrappers.<Device>lambdaUpdate()
                    .set(Device::getOnline, false)
                    .eq(Device::getDeviceId, event.getDeviceID()));
        } catch (Exception e) {
            log.error("设备离线监听器发生异常:{}", e.getMessage());
            e.printStackTrace();
        }finally {
            LOCK.unlock();
        }
    }
}
